package com.kungfuhacking.wristbandpro.location.presenter;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.kungfuhacking.wristbandpro.base.bean.Basebean;
import com.kungfuhacking.wristbandpro.base.bean.HttpListResult;
import com.kungfuhacking.wristbandpro.base.bean.RequestBean;
import com.kungfuhacking.wristbandpro.base.presenter.BasePresenter;
import com.kungfuhacking.wristbandpro.location.activity.WristbandSettingActivity;
import com.kungfuhacking.wristbandpro.location.bean.DeviceEntity;
import com.kungfuhacking.wristbandpro.location.bean.OldEntity;
import com.kungfuhacking.wristbandpro.location.view.ILocationView;
import com.kungfuhacking.wristbandpro.login.activity.LoginActivity;
import com.kungfuhacking.wristbandpro.my.activity.AddOldActivity;
import com.kungfuhacking.wristbandpro.net.BaseListObserver;
import com.kungfuhacking.wristbandpro.net.BaseNoTObserver;
import com.kungfuhacking.wristbandpro.net.RetrofitHttpUtil;
import com.kungfuhacking.wristbandpro.utils.AbDateUtil;
import com.kungfuhacking.wristbandpro.utils.Constant;
import com.kungfuhacking.wristbandpro.utils.LogUtil;

import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 定位presenter
 * Created by Aaron on 17/4/13.
 */

public class ILocationPresenter extends LocationPresenter implements BasePresenter {

    //定位间隔时间10秒
    private static final long LOCATION_INTERVAL_TIME = 10;
    private ILocationView iLocationView;
    private static final String LOCATION_TYPE_NORMAL = "";//loc 定位
    private static final String LOCATION_TYPE_WIFI = "wifi";//loc 定位
    private static final String LOCATION_TYPE_GPS = "gps";//gps 定位
    public boolean needShowLocationErr = true; //定位出错时 是否需要弹出定位出错提示
    public boolean needMoveToLocation = true; //第一次定位，需要移动到定位点
    private String TAG = getClass().getSimpleName();
    private String currentPhoneNum; //当前的手表电话号码
    private boolean isOnline;
    //    private String oldName;
    private boolean isShowLocationLoading;
    private String currentOldName;
    private double lastLat;
    private double lastLng;
    private OldEntity oldEntity;
    private Disposable loopSubscribe;
    private String currentLocationType;

    public ILocationPresenter(ILocationView iLocationView) {
//        LogUtil.d(TAG, "    注册  event  事件    ");
//        EventBus.getDefault().register(this);
//        needShowLocationErr = true;
//        needMoveToLocation = true;
        this.iLocationView = iLocationView;
    }

    public void getLocationInfo() {
        if (!TextUtils.isEmpty(iLocationView.getSp().getString(Constant.CURRENTOLDID, ""))) {//当前有选中的老人

            if (Constant.POWER_ADMIN == iLocationView.getSp().getInt(Constant.LEVEL, -1)
                    || Constant.POWER_PARENT == iLocationView.getSp().getInt(Constant.LEVEL, -1)) {
                //有权限, 获取孩子数据
                iLocationView.pageWithPermissionAndSN();
                currentLocationType = LOCATION_TYPE_NORMAL;
                isShowLocationLoading = false;
                loopLocation();//轮询定位 loc模式定位
            } else {
                //没有权限
                iLocationView.pageNoPermission();
                iLocationView.showErr("权限等级不够,请联系老人管理员");
            }
        } else {
            //没有选择过老人, 获取所有老人信息  和 权限
            getAllOldInfo();
        }

    }

    /**
     * 获取所有老人的信息
     */
    private void getAllOldInfo() {

        JSONObject j = new JSONObject();
        j.put("token", iLocationView.getToken());
        RetrofitHttpUtil.getInstance().getOldAndWatch(new BaseListObserver<OldEntity>() {
            @Override
            public void onHandleSuccess(List<OldEntity> oldEntity) {
                iLocationView.hideLoading();
                handOldInfo(oldEntity);
            }

            @Override
            public void onHandleError(String message) {
                iLocationView.hideLoading();
                iLocationView.showErr(message);
            }

            @Override
            public void onReLogin(String message) {
                iLocationView.showErr(message);
                iLocationView.hideLoading();
                iLocationView.nextActivityWithSingleTask(LoginActivity.class);
            }

            @Override
            public void onSubscribe(Disposable d) {
                compositeDisposable.add(d);
                iLocationView.showLoading("获取中...");
            }
        }, new RequestBean().setData(j.toString()));

    }

    /**
     * 处理所有绑定的老人的信息
     */
    private void handOldInfo(List<OldEntity> oldEntity) {
        if (oldEntity == null) {
            iLocationView.showErr("未获取到绑定老人数据");
            return;
        }

        if (oldEntity.size() < 1) {
            //没有绑定过老人 (跳到绑定老人的页面)
            Bundle bundle = new Bundle();
            bundle.putBoolean("cancle", false);
            iLocationView.nextActivityWithBundle(AddOldActivity.class, bundle);
            return;
        }

        //默认选择第一个
        OldEntity entity = oldEntity.get(0);

        if (entity == null) {
            iLocationView.locationErr();
            iLocationView.showErr("未获取到绑定老人数据");
            return;
        }

        SharedPreferences.Editor edit = iLocationView.getSp().edit();
        edit.putString(Constant.CURRENTOLDID, entity.getId());
        edit.putString(Constant.CURRENTOLDNAME, entity.getName());
        edit.putInt(Constant.LEVEL, entity.getLevel());
        edit.apply();
        iLocationView.setTitleName(entity.getName());
        if (Constant.POWER_ADMIN == entity.getLevel() || Constant.POWER_PARENT == entity.getLevel()) {
            //先判断等级是否够  再判断sn码是否存在
            if (entity.getDevice() == null) {
                iLocationView.showErr("设备信息错误");
                return;
            }

            if (TextUtils.isEmpty(entity.getDevice().getSn())) {
                iLocationView.pageWithPermissionNoSN();
                iLocationView.showErr("请先给老人绑定手表");
                return;
            }

            // 如果有选择过孩子 则需要延迟发送定位请求(因为有发过定位请求)
            currentLocationType = LOCATION_TYPE_NORMAL;
            isShowLocationLoading = true;
            loopLocation();

        }

    }

    /**
     * 获取老人的位置
     */
    private void loopLocation() {

//        Log.d(TAG, "获取老人的位置信息~~~");

        if (isShowLocationLoading) {
            iLocationView.showLoading("定位中...");
            iLocationView.canCancle();//可以取消定位的进度框
        }

        //每隔10秒发一次定位请求
        loopSubscribe = Observable.interval(0, LOCATION_INTERVAL_TIME, TimeUnit.SECONDS).map(new Function<Long, Integer>() {
            @Override
            public Integer apply(Long aLong) throws Exception {
                JSONObject j = new JSONObject();
                j.put("token", iLocationView.getToken());
                j.put("id", iLocationView.getSp().getString(Constant.CURRENTOLDID, ""));
                j.put("locationtype", currentLocationType);

                RetrofitHttpUtil
                        .getInstance()
                        .getOldLoc(new RequestBean().setData(j.toString()))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(
                                new BaseListObserver<OldEntity>() {
                                    @Override
                                    public void onHandleSuccess(List<OldEntity> t) {
                                        LogUtil.d(TAG, "定位成功  定位方式:==== >" + currentLocationType);
                                        iLocationView.hideLoading();
                                        setLocationInfo(t);
                                    }

                                    @Override
                                    public void onHandleError(String message) {
//                                        iLocationView.showErr(message);
                                        LogUtil.d(TAG, "定位错误 : " + message);
                                        iLocationView.hideLoading();
                                    }

                                    @Override
                                    public void onReLogin(String message) {
                                        stopLoopLcation();
                                        iLocationView.showErr(message);
                                        iLocationView.hideLoading();
                                        iLocationView.nextActivityWithSingleTask(LoginActivity.class);
                                    }

                                    @Override
                                    public void onSubscribe(Disposable d) {
                                        compositeDisposable.add(d);
                                    }
                                });

                return 1;
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe();

    }

    /**
     * 获取定位的信息
     *
     * @param t 定位信息
     */
    private void setLocationInfo(List<OldEntity> t) {

        if (t == null || t.size() < 1) {
            iLocationView.showErr("定位失败");
            iLocationView.locationErr();
            return;
        }

        oldEntity = t.get(0);

        if (oldEntity == null) {
            iLocationView.showErr("定位失败");
            iLocationView.locationErr();
            return;
        }

        //设置用户数据
        setOldData(oldEntity);

//        if (LOCATION_TYPE_GPS.equals(currentLocationType)) {//gps定位 无需操作, 只是请求而已
        currentLocationType = LOCATION_TYPE_NORMAL;//改为正常定位模式
//            return;
//        }

        DeviceEntity device = oldEntity.getDevice();
        currentOldName = oldEntity.getName();
        if (device == null) {
            if (needShowLocationErr) {
                needShowLocationErr = false;
                iLocationView.showErr("定位失败");
                needMoveToLocation = true;//定位失败后 也要重置是否定位到定位点
            }
            iLocationView.locationErr();
            return;
        }

        //当前的手表电话号码
        currentPhoneNum = device.getPhoneNum();

        if (TextUtils.isEmpty(device.getSn())) {
            iLocationView.pageWithPermissionNoSN();
            return;
        }

        if (TextUtils.isEmpty(device.getLatitude()) ||
                TextUtils.isEmpty(device.getLongitude()))
            return;

        lastLat = Double.parseDouble(device.getLatitude());
        lastLng = Double.parseDouble(device.getLongitude());
        updatePoint(lastLat, lastLng);
        if (needMoveToLocation) {//只有第一次定位才 移动到定位坐标点
            move2Location(lastLat, lastLng);
            needMoveToLocation = false;
        }
        needShowLocationErr = true;
    }

    /**
     * 更新坐标点
     *
     * @param lat
     * @param lng
     */
    private void updatePoint(double lat, double lng) {
        if (aMap == null)
            return;

        aMap.clear();

        LatLng location = new LatLng(lat, lng);
        addCircle(location, 100f);//添加定位精度圈
        addMarker(location);
    }


    /**
     * 定位
     */
    private void move2Location(double lat, double lng) {
        if (aMap == null)
            return;

//        aMap.clear();

        LatLng location = new LatLng(lat, lng);
//        addCircle(location, 100f);//添加定位精度圈
//        addMarker(location);
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 16));//移动到location位置,并设置缩放比例
    }

    /**
     * 添加精度圈
     *
     * @param latlng 坐标
     * @param radius 半径
     */
    private void addCircle(LatLng latlng, double radius) {
//        Log.e(TAG, "精度圈的大小:" + radius);
        CircleOptions options = new CircleOptions();
        options.strokeWidth(1f);
//        options.fillColor(getResources().getColor(R.color.color_location));
        options.fillColor(FILL_COLOR);
        options.strokeColor(STROKE_COLOR);
        options.center(latlng);
        options.radius(radius);
        aMap.addCircle(options);
    }

    private void addMarker(LatLng latlng) {
        mLocMarker = aMap.addMarker(new MarkerOptions().position(latlng)
                .title(currentOldName)
                .icon(BitmapDescriptorFactory.fromBitmap(iLocationView.getMarketBitmap())).anchor(0.5f, 0.5f));
    }

    /**
     * 设置老人数据
     *
     * @param oldEntity 老人信息
     */
    private void setOldData(OldEntity oldEntity) {
        //设置标题上老人的名字
        iLocationView.setTitleName(oldEntity.getName());

        if (oldEntity.getDevice() == null) {
            iLocationView.locationErr();
            return;
        }

        if (TextUtils.isEmpty(oldEntity.getDevice().getLocation()))
            aMap.clear();

        //设置老人的昵称 和定位时间
        iLocationView.setLocationName(oldEntity.getName() + "   "
                + AbDateUtil.getStringByFormat(oldEntity.getDevice().getUpdateTime(), AbDateUtil.dateFormatYMDHMS));

        //设置定位 位置
        iLocationView.setLocationAddress(TextUtils.isEmpty(oldEntity.getDevice().getLocation()) ? "暂无定位" : oldEntity.getDevice().getLocation());
        //电量
        iLocationView.setLocationBatteryView(oldEntity.getDevice().getBattery());
        //定位类型
        iLocationView.setLocationType(oldEntity.getDevice().getProvider());
        //定位信号强度, 是否在线
        iLocationView.setIsOnline(oldEntity.getDevice().isOnline());
        iLocationView.setIsOnlinePic(oldEntity.getDevice().getGsm());
        isOnline = oldEntity.getDevice().isOnline();

    }

    /**
     * 设置老人弹出框的信息好背景
     */
    @Override
    public View getInfoWindow(Marker marker) {
        return iLocationView.getMarkerView(currentOldName);
    }

    /**
     * 设置老人弹出框的信息好背景
     */
    @Override
    public View getInfoContents(Marker marker) {
        return iLocationView.getMarkerView(currentOldName);
    }

    /**
     * 点击定位按钮 gps定位
     */
    public void reLocation() {
        //GPS定位
        stopLoopLcation();//停止之前的轮询定位
        currentLocationType = LOCATION_TYPE_GPS;
        isShowLocationLoading = true;
        move2Location(lastLat, lastLng);
        loopLocation();//开始新的轮询定位
    }

    /**
     * 点击底部定位按钮 wifi定位
     */
    public void reBottonLocation() {
        stopLoopLcation();//停止之前的轮询定位
        currentLocationType = LOCATION_TYPE_WIFI;
        isShowLocationLoading = true;
        move2Location(lastLat, lastLng);
        loopLocation();//开始新的轮询定位
    }

    /**
     * 拨打手环电话
     */
    public void callOld(AlertDialog.Builder builder) {

        if (TextUtils.isEmpty(currentPhoneNum)) {
            iLocationView.showErr("请给手表安装SIM卡,并在手表状态页面设置");
            return;
        }

        builder.setMessage(currentPhoneNum).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).setPositiveButton("呼叫", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                dialog.dismiss();
                //拨打电话
                Intent intent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + currentPhoneNum));
                iLocationView.nextActivityWithIntent(intent);

            }
        }).show();
    }

    public void settingActiviyt() {
        Bundle bundle = new Bundle();
        bundle.putParcelable("oldEntity", oldEntity);
        iLocationView.nextActivityWithBundle(WristbandSettingActivity.class, bundle);
    }

    /**
     * 停止轮询定位
     */
    public void stopLoopLcation() {
        if (loopSubscribe != null) {
            loopSubscribe.dispose();
            Log.e(TAG, "   ==   停止  轮询 定位   ==");
        }
    }

    public void findWatch() {

        if (TextUtils.isEmpty(iLocationView.getSp().getString(Constant.CURRENTOLDID, ""))) {
            iLocationView.showErr("请先绑定或选择老人");
            return;
        }

        if (!isOnline) {
            iLocationView.showErr("当前手表关机,无法查找手表");
            return;
        }

        JSONObject j = new JSONObject();
        j.put("token", iLocationView.getSp().getString(Constant.TOKEN, ""));
        j.put("id", iLocationView.getSp().getString(Constant.CURRENTOLDID, ""));

        RetrofitHttpUtil.getInstance().findWatch(new BaseNoTObserver<Basebean>() {
            @Override
            public void onHandleSuccess(Basebean basebean) {
                iLocationView.hideLoading();
            }

            @Override
            public void onHandleError(String message) {
                iLocationView.showErr(message);
                iLocationView.hideLoading();
            }

            @Override
            public void onReLogin(String message) {
                iLocationView.showErr(message);
                iLocationView.hideLoading();
                iLocationView.nextActivityWithSingleTask(LoginActivity.class);
            }

            @Override
            public void onSubscribe(Disposable d) {
                iLocationView.showLoading("查找中....");
                compositeDisposable.add(d);
            }
        }, new RequestBean().setData(j.toString()));

    }

    /**
     * 解绑手表
     */
    public void unwrapWatch() {

        JSONObject j = new JSONObject();
        j.put("id", iLocationView.getSp().getString(Constant.CURRENTOLDID, ""));
        j.put("token", iLocationView.getToken());

        RetrofitHttpUtil.getInstance().getService().delWatch(new RequestBean().setData(j.toString())).flatMap(
                new Function<Basebean, Observable<HttpListResult<OldEntity>>>() {
                    @Override
                    public Observable<HttpListResult<OldEntity>> apply(Basebean basebean) throws Exception {

                        if (basebean.getCode() != 0)
                            iLocationView.showErr(basebean.getCode_msg());

                        JSONObject json = new JSONObject();
                        json.put("token", iLocationView.getToken());
                        return RetrofitHttpUtil.getInstance().getService().getChildernAndWatch(new RequestBean().setData(json.toString()));

                    }

                }

        ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<HttpListResult<OldEntity>>() {
                    @Override
                    public void accept(HttpListResult<OldEntity> oldEntityHttpListResult) throws Exception {

                        if (oldEntityHttpListResult == null)
                            return;

                        if (oldEntityHttpListResult.getCode() == 0)
                            handOldInfo(oldEntityHttpListResult.getData());
                        else
                            iLocationView.showErr(oldEntityHttpListResult.getCode_msg());

                    }
                });

    }

    @Override
    public void clearRequest() {
//        if (locationDisposable != null)
//            locationDisposable.dispose();
        stopLoopLcation();//停止轮询定位
        compositeDisposable.clear();
    }
}
